package org.seeplnframework.skyeye.common.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * @author liuweilong
 * @date 2022/9/21 7:13 PM
 * @description
 */
@Slf4j
public class RequestUtils {
    public static String getCurrentUrl() {
        String url = MDC.get("url");
        if (Objects.nonNull(url)) {
            return url;
        }
        HttpServletRequest request = getHttpRequest();
        if (request == null) return null;
        return request.getRequestURI();
    }

    private static HttpServletRequest getHttpRequest() {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (Objects.isNull(requestAttributes)) {
            return null;
        }
        return requestAttributes.getRequest();
    }

    public static String getCurrentLoginUserId() {
        //目前还没有
        String userId = MDC.get("userId");
        if (Objects.nonNull(userId) && !userId.isEmpty()) {
            return userId;
        }

        //旧版在服务层解析token
        HttpServletRequest request = getHttpRequest();
        if (request == null) {
            return null;
        }

        //新版gateway通过header传过来
        userId = request.getHeader("userId");
        if (Objects.nonNull(userId) && !userId.isEmpty()) {
            return userId;
        }

        Object tokenDTO = request.getAttribute("tokenDTOInRequest");
        String json = JSON.toJSONString(tokenDTO);
        SimpleTokenDTO simpleTokenDTO = JSONObject.parseObject(json, SimpleTokenDTO.class);
        if (Objects.isNull(simpleTokenDTO)) {
            return null;
        }
        return simpleTokenDTO.getUser();
    }

    @Data
    private static class SimpleTokenDTO {
        private String user;
    }
}